﻿using Coldairarrow.Business.BTB_StaffUsers;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Entity.UserDTO;
using Coldairarrow.Util;
using Coldairarrow.Util.Config;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.BTB_StaffUsers
{
    [Route("/BTB_StaffUsers/[controller]/[action]")]
    public class BTB_StaffUserController : BaseApiController
    {
        #region DI
        readonly IConfigsService _configsService;
        private readonly JwtOptions _jwtOptions;
        public BTB_StaffUserController(IBTB_StaffUserBusiness bTB_StaffUserBus, IConfigsService configsService, IOptions<JwtOptions> jwtOptions)
        {
            _bTB_StaffUserBus = bTB_StaffUserBus;
            _configsService = configsService;
            _jwtOptions = jwtOptions.Value;
        }

        IBTB_StaffUserBusiness _bTB_StaffUserBus { get; }

        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<BTB_StaffUser>> GetDataList(PageInput<ConditionDTO> input)
        {
            return await _bTB_StaffUserBus.GetDataListAsync(input);
        }

        #endregion

        #region 提交
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task AddDataAsync(BTB_StaffUser data)
        {
            await _bTB_StaffUserBus.AddDataAsync(data);
        }

        /// <summary>
        /// 小程序——保存用户经纬度信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task SaveSiteInfo(SetSiteDTO input)
        {
            await _bTB_StaffUserBus.SaveSiteInfoAsnyc(input);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task UserForgetPassword(UserForgetPassword data)
        {
           await _bTB_StaffUserBus.ForgetPasswordAsync(data);
        }

        #endregion


        /// <summary>
        /// 账号密码登录(获取token)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> PasswordLogin([FromBody]UserLoginInputDTO input)
        {
            string userId = await _bTB_StaffUserBus.PasswordLogin(input);

            var claims = new[]
             {
                new Claim("userId",userId)
                //new Claim("FactoryId",userInfo.FactoryId)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                string.Empty,
                string.Empty,
                claims,
                expires: DateTime.Now.AddHours(_jwtOptions.AccessExpireHours),
                signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }


        /// <summary>
        /// 验证码登录(获取token)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> VerificationLogin(LoginInputDTO2 input)
        {
            string userId = await _bTB_StaffUserBus.VerificationLogin(input);
            var claims = new[]
            {
                new Claim("userId",userId)
                //new Claim("FactoryId",userInfo.FactoryId)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                string.Empty,
                string.Empty,
                claims,
                expires: DateTime.Now.AddHours(_jwtOptions.AccessExpireHours),
                signingCredentials: credentials);
           
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }



        #region//微信H5公众号授权登录

        /// <summary>
        /// OpenId验证登录(获取token),未注册返回code-201
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> OpenIdLogin(OpenIdInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.OpenIdLogin(input);

            return data;
        }

        /// <summary>
        /// OpenId手机号绑定验证登录(获取token),未注册返回code-201
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> OPhoneLogin(OPhoneInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.OPhoneLogin(input);

            return data;
        }

        /// <summary>
        /// OpenId登录/注册(获取token)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> OpenIdRLogin(OpenIdRegistInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.OpenIdRegistLogin(input);

            return data;
        }

        #endregion

        #region//微信小程序授权登录

        /// <summary>
        /// OpenId验证登录(获取token),未注册返回code-201
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> AppletOpenIdLogin(OpenIdInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.AppletOpenIdsLogin(input);

            return data;
        }

        /// <summary>
        /// OpenId手机号绑定验证登录(获取token),未注册返回code-201
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> AppletOPhoneLogin(OPhoneInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.AppletOPhoneLogin(input);

            return data;
        }

        /// <summary>
        /// OpenId登录/注册(获取token)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> AppletOpenIdRLogin(OpenIdRegistInputDTO input)
        {
            string data = "";

            data = await _bTB_StaffUserBus.AppletOpenIdRegistLogin(input);

            return data;
        }

        #endregion

        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name = "input" >手机号</param >
        /// <returns></returns >
        [HttpPost]
        [AllowAnonymous]
        public IActionResult ReturnCode([FromBody]PhoneInput input)
        {
            Random random = new Random();
            string code = random.Next(100000, 999999).ToString();
            string ff = "";
            string keyId = _configsService.GetKeyValue("AccessKeyId");
            string keyScrect = _configsService.GetKeyValue("AccessKeySecret");
            string singName = _configsService.GetKeyValue("SignName");
            string tempCode = _configsService.GetKeyValue("TemplateCode");
            if (keyId.IsNullOrEmpty() || keyScrect.IsNullOrEmpty() || singName.IsNullOrEmpty() || tempCode.IsNullOrEmpty())
            {
                throw new BusException("短信配置错误，请联系管理员！", 420);
            }

            bool IsCode = Util.Helper.SMSVerification.SendSms(keyId, keyScrect, singName, tempCode, input.Phone, code, out ff);
            var res = new
            {
                msg = "验证码发送成功",
                success = true,
                errorCode = 0,
                data = code.ToMD5String()
            };

            if (!IsCode)
            {
                if (ff.IsNullOrEmpty())
                {
                    throw new BusException("验证码发送失败，请稍后再试", errorCode: -1);
                }
                else
                {
                    throw new BusException(ff, errorCode: -2);
                }     
            }
            return JsonContent(res.ToJson());
        }

        public class PhoneInput
        { 
            public string Phone { get; set; }
        }

        #region 获取微信登陆openid和session_key
        /// <summary>
        /// 小程序获取微信登陆openid
        /// </summary>
        /// <param name="user">用户注册后的id，用于换取openid的code码</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public string GetXCXOpenId(User user)
        {
            return  _bTB_StaffUserBus.GetOpenId(user);
        }
        #endregion

        #region 获取微信登陆openid和session_key
        /// <summary>
        ///  公众号获取微信登陆openid
        /// </summary>
        /// <param name="user">用户注册后的id，用于换取openid的code码</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> GetGZHOpenId(User user)
        {
            return await _bTB_StaffUserBus.SaveGZHData(user);
        }

        #endregion
    }
}